/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace Oceanside
{
    public partial class CreditCardEntryWindow : ModalWindow
    {
        private static bool _isVoiceAuth = false;


        /// <summary>
        /// 
        /// </summary>
        public CreditCardEntryWindow(bool isVoiceAuth = false)
            : base()
        {
            _isVoiceAuth = isVoiceAuth;

            PosWindow.MainPosWindow.Topmost = false;
            InitializeComponent();
            this.Closing += new System.ComponentModel.CancelEventHandler(MessageBox_Closing_NOTHROW);

            ///All keypad buttons are tied to the same event handler.
            button1.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button2.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button3.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button4.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button5.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button6.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button7.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button8.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button9.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            buttonCl.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            button11.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            buttonOk.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            buttonCncl.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            buttonBack.MouseDown += new MouseButtonEventHandler(KeypadButton_MouseDown_NOTHROW);
            _pan = "";
            _expire = "";
            _hasCompleteInformation = false;
        }

        void MessageBox_Closing_NOTHROW(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                ModalDialogIsOpen = false;
                CurrentlyOpenInstance = null;
#if !_DEBUG
                PosWindow.MainPosWindow.Topmost = true;

#endif
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_HOWMANY_CLOSING, exc);
            }
        }
        private enum CC_ENTRY_FORM_STATE_ENUM
        {
            GET_DATE,
            GET_PAN,
            VOICE_AUTH,
        }

        private CC_ENTRY_FORM_STATE_ENUM _currentKeypadCCEntryState = CC_ENTRY_FORM_STATE_ENUM.GET_DATE;


        private static string _pan = "";
        public static string Pan
        {
            get { return CreditCardEntryWindow._pan; }
            set { CreditCardEntryWindow._pan = value; }
        }
        private static string _expire = "";
        public static string Expire
        {
            get { return CreditCardEntryWindow._expire; }
            set { CreditCardEntryWindow._expire = value; }
        }

        private static string _voiceAuthCode = "";
        public static string VoiceAuthCode
        {
            get { return CreditCardEntryWindow._voiceAuthCode; }
            set { CreditCardEntryWindow._voiceAuthCode = value; }
        }

        private static bool _hasCompleteInformation = false;
        public static bool HasCompleteInformation
        {
            get { return CreditCardEntryWindow._hasCompleteInformation; }
            set { CreditCardEntryWindow._hasCompleteInformation = value; }
        }
        private string _guiKeyPressedString = "";

        private static ScanCodes _scanCodeFormatter = new ScanCodes();

        private int GetMaxStringEntryLength()
        {
            if (_currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.GET_DATE)
            {
                return 4;
            }
            else if (_guiKeyPressedString.Length > 0 && _guiKeyPressedString[0] == '3')
            {
                return 15;
            }
            else
            {
                return 16;
            }
        }

        /// <summary>
        /// Handles the events when a keypad button is pressed down.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void KeypadButton_MouseDown_NOTHROW(object sender, MouseButtonEventArgs e)
        {
            try
            {
                e.Handled = true;
                int maxLen = GetMaxStringEntryLength();
                int enteredLength = _guiKeyPressedString.Length;

                ///Grab the keyboard key
                ShineButton_124_124 key = sender as ShineButton_124_124;
                UInt32 val = Convert.ToUInt32(key.Tag);
                System.Windows.Forms.Keys keyVal = (System.Windows.Forms.Keys)val;

                ////There are 15 digits in a mastercard account number and 16 in all others.
                if (keyVal == System.Windows.Forms.Keys.Enter)
                {
                    if (enteredLength == maxLen || _currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.VOICE_AUTH)
                    {
                        if (_currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.GET_DATE)
                        {
                            textBoxMessage.Text = "";
                            labelMessage.Content = "Enter the Account Number";
                            _currentKeypadCCEntryState = CC_ENTRY_FORM_STATE_ENUM.GET_PAN;
                            _expire = _guiKeyPressedString;
                            _guiKeyPressedString = "";
                        }
                        else if (_currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.GET_PAN)
                        {
                            textBoxMessage.Text = "";
                            _pan = _guiKeyPressedString;
                            _guiKeyPressedString = "";

                            if (_isVoiceAuth)
                            {
                                labelMessage.Content = "Enter the Voice Auth Code";
                                _currentKeypadCCEntryState = CC_ENTRY_FORM_STATE_ENUM.VOICE_AUTH;
                            }
                            else
                            {
                                _hasCompleteInformation = true;
                                this.Close();
                            }
                        }
                        else if (_currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.VOICE_AUTH)
                        {
                            _voiceAuthCode = _guiKeyPressedString;
                            _guiKeyPressedString = "";
                            _hasCompleteInformation = true;
                            this.Close();
                        }
                    }
                }
                else if (keyVal == System.Windows.Forms.Keys.Clear)
                {
                    _guiKeyPressedString = "";
                    textBoxMessage.Text = "";
                }
                else if (keyVal == System.Windows.Forms.Keys.Cancel)
                {
                    this.Close();
                }
                else if (keyVal == System.Windows.Forms.Keys.Back)
                {
                    if (_guiKeyPressedString.Length > 0)
                    {
                        _guiKeyPressedString = _guiKeyPressedString.Substring(0, _guiKeyPressedString.Length - 1);
                    }
                }
                else
                {
                    if (_isVoiceAuth && _currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.VOICE_AUTH)
                    {
                        _guiKeyPressedString += _scanCodeFormatter.ScancodeToAsciiStrChar(keyVal);

                    }
                    else if (enteredLength < maxLen)
                    {
                        _guiKeyPressedString += _scanCodeFormatter.ScancodeToAsciiStrChar(keyVal);
                    }
                }

                if (_currentKeypadCCEntryState == CC_ENTRY_FORM_STATE_ENUM.VOICE_AUTH)
                {
                    textBoxMessage.Text = _guiKeyPressedString;
                }
                else
                {
                    DisplayGuiWindowBlanks();
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_CC_KEYPAD_MOUSE_DWN, exc);
            }
        }

        /// <summary>
        /// This function will display '*' characters in the credit card number field of the popup keypad that is
        /// used by staff to enter a credit card when they are not able to use the MSR reader itself.
        /// </summary>
        private void DisplayGuiWindowBlanks()
        {
            string blanks = "";

            if (_guiKeyPressedString.Length > 0 && _guiKeyPressedString[0] == '3')
            {
                for (int idx = 0; idx < _guiKeyPressedString.Length; idx++)
                {
                    if (idx == 4 || idx == 10)
                    {
                        blanks += "-";
                    }
                    blanks += "X";
                }
            }
            else if (_guiKeyPressedString != null)
            {
                for (int idx = 0; idx < _guiKeyPressedString.Length; idx++)
                {
                    if (idx == 4 || idx == 8 || idx == 12)
                    {
                        blanks += "-";
                    }
                    blanks += "X";
                }
            }
            textBoxMessage.Text = blanks;
        }
    }
}
